package com.ys.controller.api.base;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bo.dto.NameValueDto;
import com.ys.config.MenuId;
import com.ys.entity.base.TbPayrollSlip;
import com.ys.entity.base.TbPayrollSlipItem;
import com.ys.entity.sys.TbCompanyBankInfo;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.base.TbPayrollSlipService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.PdfService;
import com.ys.service.sys.UploadService;
import com.ys.util.DateUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

/**
 * 工资付款单
 */
@Controller
@RequestMapping("/api/inter/tbPayrollSlip")
public class ApiInterTbPayrollSlipController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTbPayrollSlipController.class);

    @Autowired
    private CommonApiService<TbPayrollSlip> commonApiService;

    @Autowired
    private TbPayrollSlipService tbPayrollSlipService;

    @Autowired
    private PdfService pdfService;

    @RequiresPermissions("tbPayrollSlip:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TbPayrollSlip cond,String conditions){
        String _ys_createUserInfo = ConditionUtil.getConditionValue(conditions, "_ys_createUserInfo");

        if (_ys_createUserInfo != null && _ys_createUserInfo.length() != 0) {
            cond.where("t2.UserId LIKE '%" + _ys_createUserInfo + "%'" + " OR  t2.UserName LIKE '%" + _ys_createUserInfo + "%'");
        }
        cond.setOrderby("A.createTime DESC")
        .addLeftJoin("YS_ProcInst Ysp ON Ysp.bid = A.bid")//流程表
        .addField("Ysp.updateTime AS updateTime1")
        .addLeftJoin("TB_UserPayApply tbup ON tbup.id = A.UserPayApplyId")//申请表
        .addLeftJoin("TS_OrganizationInfo O ON O.OrgId = tbup.OrgId")//组织机构表
        .addField("O.OrgName AS orgName")//所属公司
        .addField("tbup.bid AS userPayApplyBid")
        .addLeftJoin("TB_CompanyBankInfo cbi ON cbi.id = A.CompanyBankId")//公司银行信息
        .addField("cbi.Vyhzh AS vyhzh,cbi.Vkhh AS vkhh,cbi.Vyhzhmc AS vyhzhmc")
        .addLeftJoin("TS_UserChange t2 on  A.CreateChangeId = t2.id")
        .addField("CONCAT(t2.UserId,'/', t2.UserName) as _ys_createUserInfo")
        .addField("(SELECT SUM(R.realityPaySlip) FROM TB_PayrollSlipItem psi LEFT JOIN TB_UserPayApplyItem upai ON upai.id = psi.UserPayApplyItemId LEFT JOIN TB_UserPaySlip R ON R.id = upai.UserPaySlipidid WHERE A.Bid = psi.PayrollSlipBid) realityPaySlip");
        return commonApiService.searchLay(cond);
    }


    /**
     * 新增
     */
    @RequiresPermissions("tbPayrollSlip:add")
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData
    ) {
        try {
            logger.info("工资付款单新增传参：" + params);
            //修改
            return tbPayrollSlipService.add(params,subData);
        } catch (Exception e) {
            logger.error("工资付款单新增出错：", e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


    /**
     * 修改
     */
    @RequiresPermissions("tbPayrollSlip:add")
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData
    ) {
        try {
            logger.info("工资付款单修改传参：" + params);
            //修改
            return tbPayrollSlipService.edit(params,subData);
        } catch (Exception e) {
            logger.error("工资付款单修改出错：", e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TbPayrollSlip cond, String conditions) throws Exception{

        cond.setPage(0).setSize(999999);
        cond.setOrderby("A.createTime DESC");
        String _ys_createUserInfo = ConditionUtil.getConditionValue(conditions, "_ys_createUserInfo");

        if (_ys_createUserInfo != null && _ys_createUserInfo.length() != 0) {
            cond.where("t2.UserId LIKE '%" + _ys_createUserInfo + "%'" + " OR  t2.UserName LIKE '%" + _ys_createUserInfo + "%'");
        }
        cond.setOrderby("A.createTime DESC")
                .addLeftJoin("YS_ProcInst Ysp ON Ysp.bid = A.bid")//流程表
                .addField("Ysp.updateTime AS updateTime1")
                .addLeftJoin("TB_UserPayApply tbup ON tbup.id = A.UserPayApplyId")//申请表
                .addLeftJoin("TS_OrganizationInfo O ON O.OrgId = tbup.OrgId")//组织机构表
                .addField("O.OrgName AS orgName")//所属公司
                .addField("tbup.bid AS userPayApplyBid")
                .addLeftJoin("TB_CompanyBankInfo cbi ON cbi.id = A.CompanyBankId")//公司银行信息
                .addField("cbi.Vyhzh AS vyhzh,cbi.Vkhh AS vkhh,cbi.Vyhzhmc AS vyhzhmc")
                .addLeftJoin("TS_UserChange t2 on  A.CreateChangeId = t2.id")
                .addField("CONCAT(t2.UserId,'/', t2.UserName) as _ys_createUserInfo")
                .addField("(SELECT SUM(R.realityPaySlip) FROM TB_PayrollSlipItem psi LEFT JOIN TB_UserPayApplyItem upai ON upai.id = psi.UserPayApplyItemId LEFT JOIN TB_UserPaySlip R ON R.id = upai.UserPaySlipidid WHERE A.Bid = psi.PayrollSlipBid) realityPaySlip");

        List<Map<String, Object>> listData = cond.queryMap();


        List<YsCol> listField = new YsCol()
                .setMenuId(MenuId.TB_PayrollSlip)
                .setFrontShow(YsColEnum.FrontShow.SHOW.value)
                .setOrderby("A.SortNo asc")
                .queryList();

        ExportExcelUtils<TbPayrollSlip> util = new ExportExcelUtils<TbPayrollSlip>(new TbPayrollSlip());

        String toFilePath = util.exportExcel(listData, listField, "工资付款单表");
        UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }

    @RequestMapping("/exportxq")
    @ResponseBody
    public R exportxq(HttpServletRequest request,@RequestParam("bid") String bid) throws Exception{
        List<Map<String, Object>> listData = new TbPayrollSlipItem()
                .setPayrollSlipBid(bid)
                .addField("A.vbz AS vbzzj")//详情备注
                .addLeftJoin("TB_UserPayApplyItem upai ON upai.id = A.UserPayApplyItemId")//员工申请表详情
                .addLeftJoin("TB_UserPaySlip R ON R.id = upai.UserPaySlipidid")//员工工资表
                .addField("R.pointMonth AS pointMonth")//发薪月份
                .addField("SUBSTRING(CONVERT(varchar, DATEADD(MONTH,1,R.pointMonth + '-01'), 23),0,8) AS payDate")//发薪年月
                .addField("R.wagesPay AS wagesPay")//应发工资
                .addField("R.needPaySlip AS needPaySlip")//应付工资
                .addField("R.personalTax AS personalTax")//个人所得税
                .addField("R.realityPaySlip AS realityPaySlip")//实发工资

                .addLeftJoin("TS_UserInfo U ON U.UserId = R.UserId")//用户信息表
                .addField("(U.UserId + '/' + U.UserName) AS userName")//工号/姓名
                .addLeftJoin("TS_OrganizationInfo oi ON oi.OrgId = U.DeptId")//组织机构表
                .addField("oi.OrgName AS deptName")//部门

                .addLeftJoin("THR_UserArchives UAS ON UAS.UserId = R.UserId")//用户档案表
                .addField("UAS.UserState AS userState")//员工状态

                .addLeftJoin("TS_OrganizationInfo O ON O.OrgId = R.OrgId")//组织机构表
                .addField("O.OrgName AS orgName")//所属公司
                .addLeftJoin("TS_OrganizationAccount oa ON oa.OrgId = U.DeptId")//部门绑定账号
                .addLeftJoin("THR_OperateCompanyApply THRO ON  THRO.Vgsbm = oa.Vgsbm")
                .addField("oa.Vgsbm AS vgsbm,THRO.vgsjc AS vgsjc")//运营公司

                .addLeftJoin("TS_UserBankInfo ubi ON  ubi.UserId = U.UserId")
                .addField("ubi.vyhzh AS ygvyhzh,ubi.vkhh AS ygvkhh,ubi.vyhzhmc AS ygvyhzhmc")//收款信息

                .addLeftJoin("TB_UserMonthPerformance MP ON MP.Id = R.MonthPerformanceId")//员工月度绩效信息表
                .addField("MP.Rank AS rank")//岗位职级
                .addField("MP.Type AS type")//岗位工种(0总经理 1副总经理 2责任月薪型员工 3绩效提奖型员工 4研发人员)

                .addLeftJoin("TB_JobLevel JB ON JB.Id = R.RoleLevelId")//岗位职级管理表
                .addField("JB.Category AS category")//岗位类别
                .addField("JB.Categories AS categories")//职级大类(0A 1B 2C 3D 4P)
                .addField("A.id AS userPayApplyItemId")//id
                .queryMap();

        List<YsCol> listField = new YsCol()
                .setMenuId(MenuId.TB_PayrollSlipItem)
                .setFrontShow(YsColEnum.FrontShow.SHOW.value)
                .setOrderby("A.SortNo asc")
                .queryList();

        ExportExcelUtils<TbPayrollSlipItem> util = new ExportExcelUtils<TbPayrollSlipItem>(new TbPayrollSlipItem());

        String toFilePath = util.exportExcel(listData, listField, "工资付款单详情表");
        UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }


    /**
     * 删除工资付款单
     */
    @PostMapping("/toDel")
    @ResponseBody
    public R toDel(Long id){
        try {
            return tbPayrollSlipService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败，请联系客服");
        }
    }

    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tbPayrollSlipService.flowPass(id, ShiroUtils.getUserId());
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("服务器正在开小差，请联系客服");
        }
    }

    /**
     * 流转退回
     */
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){

        try {
            return tbPayrollSlipService.flowRefuse(id, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("服务器正在开小差，请联系客服");
        }
    }

    /**
     * 流转驳回
     */
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){
        try {
            return tbPayrollSlipService.flowInit(id, reason,ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("驳回出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 打印工资付款单
     * @param request
     * @param bid
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportdy")
    @ResponseBody
    public R exportdy(HttpServletRequest request,@RequestParam("bid") String bid) throws Exception{
        TbPayrollSlip tbPayrollSlip = new TbPayrollSlip().setBid(bid).queryFirst();
        //人员信息
        TsUserChange tsUserChange = new TsUserChange().setId(Long.valueOf(tbPayrollSlip.getCreateChangeId())).queryFirst();
        //付款信息
        TbCompanyBankInfo tbCompanyBankInfo = new TbCompanyBankInfo().setId(tbPayrollSlip.getCompanyBankId()).queryFirst();

        //子件数据
        BigDecimal realityPaySlip = BigDecimal.ZERO;
        List<Map<String, Object>> sonlist = new TbPayrollSlipItem()
                .setPayrollSlipBid(bid)
                .addLeftJoin("TB_UserPayApplyItem upai ON upai.id = A.UserPayApplyItemId")//员工申请表详情
                .addLeftJoin("TB_UserPaySlip R ON R.id = upai.UserPaySlipidid")//员工工资表
                .addField("R.realityPaySlip AS realityPaySlip")//实发工资
                .queryMap();
        for (Map<String, Object> son : sonlist){
            realityPaySlip = realityPaySlip.add(new BigDecimal(son.get("realityPaySlip").toString()));
        }

        List<NameValueDto> listData = new ArrayList<>();
        listData.add(new NameValueDto("单据编号",bid));
        listData.add(new NameValueDto("申请人",tsUserChange.getUserId() + "/" + tsUserChange.getUserName()));
        listData.add(new NameValueDto("申请部门",tsUserChange.getDeptName()));
        listData.add(new NameValueDto("付款账号",tbCompanyBankInfo.getVyhzhmc() + "/" + tbCompanyBankInfo.getVyhzh() + "/" + tbCompanyBankInfo.getVkhh()));
        listData.add(new NameValueDto("收款账号","员工工资卡"));
        listData.add(new NameValueDto("付款类型","经营费用→工资"));
        listData.add(new NameValueDto("付款金额",realityPaySlip.toString()));
        listData.add(new NameValueDto("付款说明",tbPayrollSlip.getVbz()));
        String url = pdfService.generatePDF(bid,"工资付款单", tbCompanyBankInfo.getVyhzhmc(), DateUtil.getYYYY_MM_DD_HH_mm_ss(tbPayrollSlip.getCreateTime()),listData);
        return R.ok(url);
    }
}
